package com.example.fruit.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.fruit.R;
import com.example.fruit.bean.Fruit;
import com.example.fruit.bean.Orders;
import com.example.fruit.util.SPUtils;
import com.example.fruit.widget.ActionBar;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 立即购买结算商品
 */
public class BuyActivity extends AppCompatActivity {
    private Activity mActivity;
    private ImageView ivImg;
    private TextView tvTitle;
    private TextView tvDate;
    private TextView tvIssuer;
    private Button btnbuy;
    private Button btnCancel;
    private ActionBar mActionBar;//标题栏
    private String[] s=new String[]{"支付宝","银行卡","微信"}; int i;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        setContentView(R.layout.activity_buy);
        ivImg = findViewById(R.id.img);
        tvTitle= findViewById(R.id.title);
        tvDate = findViewById(R.id.date);
        tvIssuer = findViewById(R.id.issuer);
        btnbuy = findViewById(R.id.btn_buy);
        btnCancel = findViewById(R.id.btn_cancel);
        mActionBar = findViewById(R.id.myActionBar);
        //侧滑菜单
        mActionBar.setData(mActivity,"结算商品", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }
            @Override
            public void onRightClick() {
            }
        });
        Fruit fruit = (Fruit) getIntent().getSerializableExtra("fruit");
        tvTitle.setText(fruit.getTitle());
        tvDate.setText(String.format("上架时间       %s",fruit.getDate()));
        tvIssuer.setText(String.format("￥ %s",fruit.getIssuer()));
        Glide.with(mActivity)
                .asBitmap()
                .skipMemoryCache(true)
                .load(fruit.getImg())
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(ivImg);
        btnbuy.setVisibility(View.VISIBLE);
    }
    public void buy(View view){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.a1);//设置图标
        builder.setTitle("请选择支付方式");//设置对话框的标题
        builder.setSingleChoiceItems(s,0,new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                i=which;
             }
        });
        builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ProgressDialog dialog2 = new ProgressDialog(mActivity);
                        dialog2.setMessage("支付中···");
                        dialog2.show();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Fruit fruit = (Fruit) getIntent().getSerializableExtra("fruit");
                                String account = (String) SPUtils.get(mActivity, SPUtils.ACCOUNT, "");
                                int have, fruitAmount;
                                fruitAmount = Integer.parseInt(fruit.getAmount());//库存数量
                                have = fruitAmount - 1;//被购买后剩余库存
                                if(fruitAmount > 1){
                                //运行内容
                                Orders orders = new Orders(account,"1", fruit.getTitle(),"S" + System.currentTimeMillis(),fruit.getIssuer(),fruit.getImg(), sf.format(new Date()));//获取总毫秒数 从1970年1月1日开始计算
                                orders.save();

                                Fruit newfirst = DataSupport.where("title = ?", fruit.getTitle()).findFirst(Fruit.class);
                                newfirst.setAmount(have + "");//修改新的库存数量
                                newfirst.save();

                                Toast.makeText(mActivity, s[i] + "支付-成功,请在我的订单中查看!", Toast.LENGTH_SHORT).show();

                                if (i == 0) {
                                    //打开支付宝
                                    try {
                                        Intent intent = new Intent(Intent.ACTION_MAIN);
                                        ComponentName cmp = new ComponentName("com.eg.android.AlipayGphone", "com.alipay.mobile.quinox.splash.ShareDispenseActivity");
                                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        intent.setComponent(cmp);
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        //异常处理
                                    }
                                }
                                if (i == 1) {
                                    //银行卡
                                    try {
                                        Uri uri = Uri.parse("http://cn.unionpay.com/upowhtml/cn/templates/quickPass/quickPass.html");
                                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        //异常处理
                                    }
                                }
                                if (i == 2) {
                                    //打开微信
                                    try {
                                        Intent intent = new Intent(Intent.ACTION_MAIN);
                                        ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        intent.setComponent(cmp);
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        //异常处理
                                    }
                                }
                                btnbuy.setVisibility(View.GONE);
                                btnCancel.setVisibility(View.VISIBLE);
                                dialog2.setMessage("支付成功！点击任意空白区域返回");
                            } else {
                                dialog2.setMessage("支付失败！点击任意空白区域返回");
                                Toast.makeText(mActivity, "支付失败,商品库存数量不足!", Toast.LENGTH_SHORT).show();
                                } }
                        }, 1500);

                    }
                }
        );
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(mActivity,"您取消了支付!", Toast.LENGTH_SHORT).show();
                    }
                }
        );
        AlertDialog a=builder.create();
        a.show();
    }
    public void QQ(View view){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.a1);//设置图标
        builder.setTitle("水果商城");//设置对话框的标题
        builder.setMessage("确定要联系客服吗？");//设置对话框的内容
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //跳转到我的资料卡
                ProgressDialog dialog3 = new ProgressDialog(mActivity);
                dialog3.setMessage("正在连接客服···");
                dialog3.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(mActivity,"如无法联系，请添加好友后再试!", Toast.LENGTH_LONG).show();
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=1632957243")));//跳转到QQ资料
                        }catch (Exception e){
                            Toast.makeText(mActivity,"请安装最新版QQ后使用此功能!", Toast.LENGTH_LONG).show();
                        }
                        dialog3.dismiss();
                    }
                }, 1500);
                btnbuy.setVisibility(View.GONE);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }
        );
        AlertDialog a=builder.create();
        a.show();  //必须show一下才能看到对话框
   }
}
